<?php

namespace App\servers;

use Elasticsearch\ClientBuilder;
use Illuminate\Support\Facades\Log;

class EsService
{
    protected static $client;

    public function __construct()
    {
        $hosts = [
            config('es.host'),    // HTTP Basic Authenticationt
        ];
        $client = ClientBuilder::create()
            ->setHosts($hosts)
            ->build();
        $this->client = $client;
    }

    /**
     * yuql
     * 获取索引
     * @param $indexName
     * @param $query
     */
    public function get_index($indexName, $query){
        try {
            $params = [
                'index' => $indexName,
                'body'  => [
                    'query' => [
                        'bool' => [
                            'must' => $query
                        ]
                    ]
                ]
            ];
            $result = self::$client->search($params);
            //提取出Es中想要的数据
            $data = $result['hits']['hits'];
            foreach ($data as $v){
                $datas[] = $v['_source'];
            }
            return $datas;
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
            return fail($exception->getMessage(),'');
        }
    }

    /**
     * Es数据同步入库
     * @param $indexName
     * @param array $indexData
     */
    public function create_index($id,$indexName,$indexData=[]){
        try {
            $params = [
                //写入的Es数据库
                'index' => $indexName,
                'id' => $id,
                'body'  => $indexData,
            ];
            dd(self::$client);
            $result = self::$client->index($params);
            if ($result){
                //同步成功写入日志
                Log::info($indexData['id'] . '数据同步成功');
            }
        }catch (\Exception $exception){
            Log::error($exception->getMessage());
            return fail($exception->getMessage(),'');
        }
    }
}
